'use strict';
const crypto = require('crypto')
const db = uniCloud.database()
let uniID = require('uni-id')

exports.main = async (event, context) => {
  uniID = uniID.createInstance({
    context
  })
  const {
    goodId,
    uniIdToken
  } = event
  const payload = await uniID.checkToken(uniIdToken)

  if (payload.code > 0) {
    return {
      code: 1001,
      msg: '用户身份验证失败，请重新登录'
    }
  }
  const uid = payload.uid
  const mechanism_id = payload.userInfo.mechanism_id
  const goods = db.collection('price-list')
  const dbCmd = db.command
  const order = db.collection('order');
  if (!goodId) {
    return {
      code: -2,
      msg: '商品信息错误'
    }
  }

  const cur_good = await goods.where({_id:dbCmd.eq(goodId)}).limit(1).get()
  console.log("当前购买",cur_good.data)
  // 计算总金额
  const totalFee = cur_good.data[0].totalFee
  const day = cur_good.data[0].day
  // 生成订单号的方式多种多样，实际应根据自己业务需求来，这里使用的是精确到秒的时间戳加用户id的hash前8位
  const outTradeNo = parseInt(Date.now() / 1000) + crypto
    .createHash('md5')
    .update(uid, 'utf-8')
    .digest('hex').substring(0, 8);
  const orderResult = await order.add({
    uid,
    outTradeNo,
    mechanism_id,
    totalFee,
    goodId,
    day,
    status: 1 // 1 - 未支付，2 - 已支付
  })
  console.log("创建订单",orderResult)
  if (!orderResult.id) {
    return {
      code: -3,
      msg: '创建订单失败，请稍后再试'
    }
  }

  return {
    outTradeNo
  }

};
